package com.backend.demo1.services;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.backend.demo1.mapper.MemberMapper;
import com.backend.demo1.mapper.RoleMapper;
import com.backend.demo1.mapper.UserMapper;
import com.backend.demo1.models.Member;
import com.backend.demo1.models.Role;
import com.backend.demo1.models.User;

@Service
public class MemberService {

    @Autowired
    private MemberMapper memberMapper;

    @Autowired
    private UserMapper userMapper; // 注入 UserMapper

     @Autowired
    private RoleMapper roleMapper; // 注入 RoleMapper



    // 插入会员
    public void insert(Member member) {
        memberMapper.insert(member);
        // 查询 Role 表以获取 name 为 user 的 id
        Role userRole = roleMapper.findByName("user");
        if (userRole != null) {
            User user = new User();
            user.setid(member.getUserId());
            user.setRoleid(userRole.getid()); // 设置 role 字段
            userMapper.updateRole(user);
        } else {
            throw new RuntimeException("Role 'user' not found in the database.");
        }
    }


    // 根据 ID 查找会员
    public Member findById(Long id) {
        return memberMapper.findById(id);
    }

    // 获取所有成年会员
    public List<Member> findAll() {
        return memberMapper.findAll();
    }

    // 更新会员信息
    public void update(Member member) {
        memberMapper.update(member);
    }

    // 删除会员信息
    public void deleteById(Long id) {
        if (memberMapper.findById(id) == null) {
            throw new IllegalArgumentException("No record found with ID: " + id);
        }
        memberMapper.deleteById(id);
    }

    // 检查是否已存在该会员（通过 userId）
    public boolean existsByUserId(Long userId) {
        return memberMapper.existsByUserId(userId) > 0;
    }
}